package com.code2roc.jarmanage.servlet.war;

import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.db.WarDB;
import com.code2roc.jarmanage.depoly.DepolyServiceFactory;
import com.code2roc.jarmanage.depoly.DepolyStatus;
import com.code2roc.jarmanage.model.*;
import com.code2roc.jarmanage.util.CommonUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import com.code2roc.jarmanage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WarListSerlvet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String projectName = ConvertUtil.convert2String(paramMap.get("projectName"));
        String sql = "1=1 and DepolyType='war'";
        if (!StringUtil.isEmpty(projectName)) {
            sql += " and projectName like '%" + projectName + "%'";
        }
        List<WarDO> entityList = WarDB.selectList(sql);
        List<WarModel> warModelList = new ArrayList<>();
        for (WarDO entity : entityList) {
            WarModel model = new WarModel();
            model = ConvertUtil.convertSameStructObj(entity, model);
            String filePath = entity.getJarPackagePath() + File.separator + "webapps" + File.separator + entity.getServiceName() + ".war";
            if (new File(filePath).exists()) {
                model.setProjectStatus(new DepolyServiceFactory().CreateDeployService().getStatus(model.getServiceName()));
            } else {
                model.setProjectStatus(DepolyStatus.UnUpload);
            }
            warModelList.add(model);
        }
        result.add("obj", warModelList);
        resp.getWriter().println(result.toString());
    }
}
